package com.gqz.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.system.UserInfo;
import com.gqz.domain.SysUser;
import com.gqz.dto.SysUserDto;
import com.gqz.mapper.SysUserMapper;
import com.gqz.service.ISysLoginService;
import com.gqz.utils.UserTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
public class SysLoginServiceImpl implements ISysLoginService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public SysUserDto login(SysUser user, HttpServletRequest request) {

        //1、校验前端传过来的用户名和密码是否为空
        if (StrUtil.isEmpty(user.getUserName())) {
            throw new RuntimeException("账号为空！");
        }
        if (StrUtil.isEmpty(user.getPassword())) {
            throw new RuntimeException("密码为空！");
        }
        //2、开始使用用户名查询数据库是否存在该用户信息
        Example example = new Example(SysUser.class);
        example.and().andEqualTo("userName", user.getUserName());
        List<SysUser> sysUsers = sysUserMapper.selectByExample(example);

        //3、判断查询返回的用户信息是否存在
        if (sysUsers == null || sysUsers.size() == 0) {
            throw new RuntimeException("用户不存在！");
        }

        //4、获取登录用户的信息
        SysUser sysUser = sysUsers.get(0);

        //5、将前端传过来的密码进行MD5加密
        String md5 = SecureUtil.md5(user.getPassword());

        //6、将加密后的密码与数据库的加密密码进行比对
        if (!md5.equals(sysUser.getPassword())) {
            throw new RuntimeException("密码错误！！");
        }

        //7、将前端需要的数据传过去
        SysUserDto user1 = new SysUserDto();
        user1.setRealName(sysUser.getRealName());
        user1.setAvatar(sysUser.getAvatar());

        // 8、将用户的信息保存到session中(注意：传入的对象是从数据库中拿到的)
        UserTools.saveUserSession(request, sysUser);

        return user1;
    }

    @Override
    public void exit(HttpServletRequest request) {
        UserTools.clearUserSession(request);
    }
}
